﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SnakeHead : MonoBehaviour 
{
    public List<Transform> bodys =new List<Transform>();
    public float velocity;
    public int step;
    int x, y;
    public Sprite[] bodycolor;
    GameObject body;
    bool stop = false;
    void Start () 
	{
       
        body = Resources.Load("Body") as GameObject;
        transform.localPosition = RandomFood.Instance.point;
        x = step;y = 0;
        InvokeRepeating("Move", 0, 1f*velocity);
        //bodys.Add(transform);
        
	}
	void Update () 
	{
        if (Input.GetKeyDown(KeyCode.W)&&y!=-step)
        {
            transform.localRotation = Quaternion.Euler(0, 0, 0);
            x = 0;y = step;
        }
        if (Input.GetKeyDown(KeyCode.S) && y != step)
        {
            transform.localRotation = Quaternion.Euler(0, 0, 180);
            x = 0; y = -step;
        }
        if (Input.GetKeyDown(KeyCode.A) && x != step)
        {
            transform.localRotation = Quaternion.Euler(0, 0, 270);
            x = -step; y = 0;
        }
        if (Input.GetKeyDown(KeyCode.D) && x != -step)
        {
            transform.localRotation = Quaternion.Euler(0,0 , 90);
            x = step; y = 0;
        }
        
      
    }
    void Move()
    {
        if (stop ==false)
        {

            Vector3 pos = transform.localPosition;
            //Vector3 worldpod = transform.position;

            transform.localPosition = new Vector3(pos.x + x, pos.y + y, 0);

            if (bodys.Count > 0 )
            {
                bodys[0].localPosition = pos;
                for (int i = bodys.Count - 1; i >= 1; i--)
                {
                    bodys[i].GetComponent<Image>().color = new Color(255, 255, 255, 255);
                    bodys[i].localPosition = bodys[i - 1].localPosition;
                }

            }
        }
    }
    void Grow()
    {
        GameObject ob = Instantiate(body,transform.parent,false) ;
        int index = bodys.Count%2 == 0 ? 0 : 1;
        ob.GetComponent<Image>().sprite = bodycolor[index];
        ob.transform.localPosition = Vector3.zero;
        ob.GetComponent<Image>().color = Color.clear;
        ob.transform.localScale = Vector3.one;
        bodys.Add(ob.transform);
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Food")
        {
            Destroy(collision.gameObject);
            RandomFood.Instance.Creat();
            Grow();
        }
        else if (collision.gameObject.tag == "Die")
        {
            stop = true;
            Debug.Log("Die");
        }
        else if (collision.gameObject.tag == "Wall")
        {
            stop = true;
            Debug.Log("WallDie");
        }
    }
}
